package com.example.slidebutton;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Alex-Zhang on 2017/11/8.
 */

public class SlideBlockButton extends  ViewGroup implements View.OnClickListener {
    //    没处理空  那就尽量不要空咯
    private String[] contents = {"在线", "商城", "ahahhaha"};

    private static final float DEFAULT_WIDTH = dp2px(200);

    private static final float DEFAULT_HEIGHT = dp2px(80);

    private int textSize = 30;

    private int textColorDisable = Color.BLUE;
    private int textColorEnable = Color.WHITE;

    //    shape资源做背景
    private int resourceIdBackground = R.drawable.background_invoicelist_head;
    private int resourceIdBlockview = R.drawable.selector_textcolor_alwayswhite;


    private View blockView;
    private TextView[] textViews;
    private ColorStateList textColor;
    private int selectedIndex = -1;
    private float mLastMotionX;

    private Rect blockViewRect;
    private boolean isTouchBlock;

    private OnTagSelectedListener onTagSelectedListener;

    public SlideBlockButton(Context context) {
        super(context);
        init(context);
    }

    public SlideBlockButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SlideBlockButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        textColor = createColorStateList();
        blockViewRect = new Rect();

        blockView = new View(context);
        blockView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        blockView.setBackgroundResource(resourceIdBlockview);
        addView(blockView);

        textViews = new TextView[contents.length];
        for (int i = 0; i < contents.length; i++) {
            TextView tempTextview = new TextView(context);
            tempTextview.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
            tempTextview.setTextColor(textColor);
            tempTextview.setTextSize(textSize);
            tempTextview.setGravity(Gravity.CENTER);
            tempTextview.setSingleLine(true);
            tempTextview.setEllipsize(TextUtils.TruncateAt.END);
            tempTextview.setText(contents[i]);
            tempTextview.setTag(i);
            tempTextview.setOnClickListener(this);
            textViews[i] = tempTextview;
            addView(textViews[i]);
        }
        setBackgroundResource(resourceIdBackground);

        selectedIndex = 0;
        textViews[selectedIndex].setEnabled(false);

    }


    private ColorStateList createColorStateList() {
        int[] colors = new int[]{textColorDisable, textColorEnable, textColorEnable};
        int[][] states = new int[3][];
        states[0] = new int[]{-android.R.attr.state_enabled};
        states[1] = new int[]{android.R.attr.state_enabled};
        states[2] = new int[]{};
        return new ColorStateList(states, colors);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.UNSPECIFIED
                || widthMode == MeasureSpec.AT_MOST) {
            widthMeasureSpec = MeasureSpec.makeMeasureSpec((int) DEFAULT_WIDTH, MeasureSpec.EXACTLY);
        }
        if (heightMode == MeasureSpec.UNSPECIFIED
                || heightMode == MeasureSpec.AT_MOST) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec((int) DEFAULT_HEIGHT, MeasureSpec.EXACTLY);
        }
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int perWidth = getMeasuredWidth() / textViews.length;
        for (int i = 0; i < textViews.length; i++) {
            TextView tv = textViews[i];
            tv.setWidth(perWidth);
            tv.setHeight(getMeasuredHeight());
            tv.layout(perWidth * i, 0, perWidth * (i + 1), getMeasuredHeight());
        }
        ViewGroup.LayoutParams lp = blockView.getLayoutParams();
        lp.width = perWidth;
        lp.height = getMeasuredHeight();
        blockView.setLayoutParams(lp);
        blockView.layout(perWidth * selectedIndex, 0, perWidth * (selectedIndex + 1), getMeasuredHeight());
    }

    @Override
    public void onClick(View v) {
        for (int i = 0; i < textViews.length; i++) {
            TextView tv = textViews[i];
            tv.setEnabled(tv != v);
            if (tv == v) {
                selectedIndex = i;
            }
        }
        startMoveAnimate();
    }

    private void startMoveAnimate() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(blockView.getX(), selectedIndex * getMeasuredWidth() / textViews.length);
        valueAnimator.setDuration(100);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                blockView.setTranslationX(value);
            }
        });
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                for (int i = 0; i < textViews.length; i++) {
                    TextView tv = textViews[i];
                    tv.setEnabled((int) tv.getTag() != selectedIndex);
                }
                if (onTagSelectedListener != null) {
                    onTagSelectedListener.onTagSelected(contents[selectedIndex], selectedIndex);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        valueAnimator.start();
    }


    private static int dp2pxInt(float dp) {
        return (int) dp2px(dp);
    }

    private static float dp2px(float dp) {
        Resources r = Resources.getSystem();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int perWidth = getMeasuredWidth() / textViews.length;
        float x = ev.getRawX();
        float y = ev.getRawY();
        Log.e("tag", "blockView ontouch::" + x);
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                blockView.getGlobalVisibleRect(blockViewRect);
                Log.e("tag", "ACTION_DOWN::" + blockViewRect.toString());
                if (blockViewRect.contains((int) x, (int) y)) {
                    isTouchBlock = true;
                }
                mLastMotionX = x;
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("tag", "ACTION_MOVE::");
                if (!isTouchBlock) {
                    break;
                }
                float dx = mLastMotionX - x;
                float tempTranslateX = blockView.getTranslationX() - dx;
                if (tempTranslateX > getMeasuredWidth() - perWidth) {
                    tempTranslateX = getMeasuredWidth() - perWidth;
                } else if (tempTranslateX < 0) {
                    tempTranslateX = 0;
                }
                blockView.setTranslationX(tempTranslateX);
                mLastMotionX = x;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_UP:
                Log.e("tag", "ACTION_UP::");
                selectedIndex = Math.round(blockView.getTranslationX() / perWidth);
                startMoveAnimate();
                isTouchBlock = false;
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    public OnTagSelectedListener getOnTagSelectedListener() {
        return onTagSelectedListener;
    }

    public void setOnTagSelectedListener(OnTagSelectedListener onTagSelectedListener) {
        this.onTagSelectedListener = onTagSelectedListener;
    }

    public interface OnTagSelectedListener {
        void onTagSelected(String description, int index);
    }
}
